package com.bibrApp.difu.actvity.order_detail_mvp;


import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bibrApp.difu.BeemIntent;
import com.bibrApp.difu.R;
import com.bibrApp.difu.Response.CoverShortResBody;
import com.bibrApp.difu.Response.OrderDetailResBody;
import com.bibrApp.difu.Response.OrderMoreDetailResBody;
import com.bibrApp.difu.Response.SignDataResBody;
import com.bibrApp.difu.Response.SignIVDataResBody;
import com.bibrApp.difu.actvity.huankuan_mvp.HuanKuanActivity;
import com.bibrApp.difu.actvity.wait_delivery_mvp.WaitDeliveryActivity;
import com.bibrApp.difu.actvity.wallet_mvp.WalletActivity;
import com.bibrApp.difu.base.BaseActivity;
import com.bibrApp.difu.fragment.jieru_mvp.JiedaiManagerBean;
import com.bibrApp.difu.proto2javabean.UtxoBean;
import com.bibrApp.difu.utils.BigdecimalUtils;
import com.bibrApp.difu.utils.CalendarUtils;
import com.bibrApp.difu.utils.ClsPublicUtils;
import com.bibrApp.difu.utils.IntentUtil;
import com.bibrApp.difu.utils.StrValidateUtils;
import com.bibrApp.difu.utils.ToastUtils;
import com.bibrApp.difu.utils.UCaculateUtils;
import com.bibrApp.difu.widget.DashBoard;
import com.bushidowallet.core.bitcoin.bip32.ExtendedKey;
import com.google.protobuf.ByteString;
import com.satoshilabs.trezor.lib.protobuf.TrezorMessageBitcoin;
import com.satoshilabs.trezor.lib.protobuf.TrezorMessageCommon;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class OrderDetailActivity extends BaseActivity<OrderDetailPresenter> implements IOrderDetailView {


    @BindView(R.id.btn_left)
    TextView tvLeft;
    @BindView(R.id.btn_right)
    TextView tvRight;
    @BindView(R.id.btn_commit)
    TextView tvCommit;
    @BindView(R.id.tv_orderid)
    TextView tvOrderId;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_money_title)
    TextView tv_money_title;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_actual_money_title)
    TextView tv_actual_money_title;
    @BindView(R.id.tv_lx_title)
    TextView tv_lx_title;
    @BindView(R.id.tv_jc_money)
    TextView tv_jc_money;
    @BindView(R.id.tv_lx)
    TextView tv_lx;
    @BindView(R.id.tv_sxf)
    TextView tv_sxf;
    @BindView(R.id.tv_drate)
    TextView tv_drate;
    @BindView(R.id.tv_yrate)
    TextView tv_yrate;
    @BindView(R.id.tv_dyrate)
    TextView tv_dyrate;
    @BindView(R.id.tv_cycle)
    TextView tv_cycle;
    @BindView(R.id.tv_coin_type)
    TextView tv_coin_type;
    @BindView(R.id.tv_zhiya)
    TextView tv_zhiya;
    @BindView(R.id.tv_createtime)
    TextView tv_createtime;
    @BindView(R.id.tv_endtime)
    TextView tv_endtime;
    @BindView(R.id.iv_status)
    ImageView ivStatus;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_jcname)
    TextView tvJcName;
    @BindView(R.id.tv_cjname)
    TextView tvCjName;
    @BindView(R.id.tv_pingtai)
    TextView tvPingtai;
    @BindView(R.id.tv_third)
    TextView tvThird;
    @BindView(R.id.dash_board)
    DashBoard dashBoard;

    private JiedaiManagerBean bean;
    private Context mContext;
    private Receiver mUsbReceiver;

    @Override
    protected void initPresenter() {
        presenter = new OrderDetailPresenter(this, this);
        presenter.init();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_detail;
    }


    @Override
    public void error(String msg) {

    }

    @Override
    public void success(String msg) {

    }

    /**
     * 0	待交割	7	待收款
     * 1	交割中	8	待补仓
     * 2	待抵押	9	待平仓
     * 3	已抵押	10	已逾期
     * 4	待还款	101	已平仓
     * 5	待付款	102	已结束
     * 6	已付款	103	已取消
     * 104 待签名 105 待审核 106违约未提币 107 已还款未提币 108 已平仓未收取手续费 109 提币中 110已还款未确认（未结束订单）
     *
     * @param item
     */
    @Override
    public void successOfGetDetail(OrderDetailResBody item) {
        if (item != null) {
            initButton(item);
            switch (item.getStatus()) {
                case 0:
                    tvStatus.setText("待交割");
                    break;
                case 8:
                    tvStatus.setText("待补仓");
                    break;
                case 1:
                    tvStatus.setText("交割中");
                    break;
                case 2:
                    tvStatus.setText("待抵押");
                    break;
                case 3:
                    tvStatus.setText("已抵押");
                    break;
                case 4:
                case 101:
                    tvStatus.setText("待还款");
                    break;
                case 5:
                    tvStatus.setText("待付款");
                    break;
                case 6:
                    tvStatus.setText("已付款");
                    break;
                case 7:
                    tvStatus.setText("待收款");
                    break;
                case 9:
                    tvStatus.setText("待平仓");
                    break;
                case 10:
                    tvStatus.setText("已逾期");
                    break;
                case 103:
                    tvStatus.setText("已取消");
                    break;
                //* 104 待签名 105 待审核 106违约未提币 107 已还款未提币 108 已平仓未收取手续费 109 提币中 110已还款未确认（未结束订单）
                case 104:
                    tvStatus.setText("待签名");
                    break;
                case 105:
                    tvStatus.setText("待审核");
                    break;
                case 109:
                    tvStatus.setText("提币中");
                    break;
                case 106:
                case 107:
                    tvStatus.setText("待提币");
                    break;
                case 108:
                    tvStatus.setText("已平仓");
                    break;
                case 110:
                    tvStatus.setText("已还款");
                    break;
                default:
                    tvStatus.setText("已结束");


            }
            tvOrderId.setText("订单号 \n" + item.getOrderNo());
            tvName.setText("对方姓名 " + StrValidateUtils.replaceNameX(item.getOtherName()));
            tv_money_title.setText("本息合计(" + item.getPawnCoinEunit() + ")");
            tv_actual_money_title.setText("借入金额(" + item.getPawnCoinEunit() + ")");
            tv_lx_title.setText("到期利息(" + item.getPawnCoinEunit() + ")");
            tv_jc_money.setText(String.valueOf(item.getLegalQuantity()));
            tv_drate.setText(item.getLegalDailyRate() * 100 + "%");
            tv_yrate.setText(item.getLegalDailyRate() * 100 * 365 + "%");
            tv_dyrate.setText(item.getPawnRate() * 100 + "%");
            if (item.getPawnCoinEunit().equalsIgnoreCase("btc")) {
//                tv_sxf.setText(item.get);
                tv_lx.setText(String.valueOf(BigdecimalUtils.getBigDecimalPointNum(item.getTotalInterest(), 8)));
                tv_money.setText(String.valueOf(BigdecimalUtils.getBigDecimalPrice(String.valueOf(item.getTotalInterest().add(item.getLegalQuantity())), 8)));
            } else {
                tv_lx.setText(String.valueOf(BigdecimalUtils.getBigDecimalPointNum(item.getTotalInterest(), 2)));
                tv_money.setText(String.valueOf(BigdecimalUtils.getBigDecimalPrice(String.valueOf(item.getTotalInterest().add(item.getLegalQuantity())), 2)));
            }
            tv_cycle.setText(item.getCycle() + "天");
            tv_coin_type.setText(item.getPawnCoinEunit());
            //借贷金额/抵押率/实时币价
            tv_zhiya.setText(String.valueOf(BigdecimalUtils.getBigDecimalPrice(String.valueOf(item.getLegalQuantity().divide(BigdecimalUtils.getBigDecimalPrice(String.valueOf(item.getLegalDailyRate()), 4), 8, RoundingMode.DOWN).divide(item.getNewPrice(), 8, RoundingMode.DOWN)), 8)));
            tv_createtime.setText(CalendarUtils.formatHisEntrustDate(item.getCreateTime()));
            tv_endtime.setText(CalendarUtils.formatHisEntrustDate(item.getRepaymentTime()));

            dashBoard.cgangePer(0.7f);

        }
    }

    @Override
    public void successOfGetMoreDetail(OrderMoreDetailResBody orderDetailResBody) {
        tvJcName.setText(orderDetailResBody.getOtherUserName());
        tvCjName.setText(orderDetailResBody.getMyName());

    }

    @Override
    public void successOfGetCoverShort(CoverShortResBody coverShortResBody) {

    }

    private SignDataResBody mSignData;

    @Override
    public void successOfGetSignData(SignDataResBody signDataResBody) {
        mSignData = signDataResBody;
        presenter.getSignDataByHash(signDataResBody.getHardWalletSignTransaction().getInputs().get(0).getPrevHash());
    }

    /**
     * BTC多签过程
     * 从后台获取:1.赎回脚本（内含所有用户的公钥）2.交易源数据（由于解码问题，改为返回未编码的交易源数据）
     */
    private List<ExtendedKey> extendedKeyList;
    private List<TrezorMessageCommon.HDNodeType> nodes;
    @Override
    public void successOfGetSignIVData(SignIVDataResBody signIVDataResBody) {
        //多签
        if(mSignData == null || mSignData.getB58PublicKeys() == null || mSignData.getB58PublicKeys().size() == 0){
            return;
        }
        if(extendedKeyList == null){
            extendedKeyList = new ArrayList<>();
        }
        extendedKeyList.clear();
        if(nodes == null){
            nodes = new ArrayList<>();
        }
        nodes.clear();
        for( int i = 0 ; i < mSignData.getB58PublicKeys().size() ; i++){
            try {
                ExtendedKey extendedKey =  ExtendedKey.ExtendedKeyParser.parse(mSignData.getB58PublicKeys().get(i),true);
                extendedKeyList.add(extendedKey);
                //"node": {
                //                                    "depth": 4,
                //                                    "fingerprint": 3110059204,
                //                                    "child_num": 13,
                //                                    "chain_code": "EWiUEWpHy8OyFPI6/pUBGydgJeNg52SCPD0Z9hlXXJg=",
                //                                    "public_key": "A1U2e4CjzwR84DzUX2CEDRioeT2ctyYWcKvX1k12rHve"
                //                                }
                TrezorMessageCommon.HDNodeType.Builder nodeBuilder = TrezorMessageCommon.HDNodeType.newBuilder();
                nodeBuilder.setDepth(extendedKey.getFingerPrint())
                        .setFingerprint(extendedKey.getFingerPrint());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        buildInput(signIVDataResBody);
        buildOutput(signIVDataResBody);
    }
    private List<TrezorMessageBitcoin.TxAck.TransactionType.TxInputType> txInputTypes = new ArrayList<>();
    private List<TrezorMessageBitcoin.TxAck.TransactionType.TxOutputType> txOutputTypes = new ArrayList<>();
    private void buildOutput(SignIVDataResBody signIVDataResBody) {

    }

    private void buildInput(SignIVDataResBody signIVDataResBody) {
        if (txInputTypes.size() > 0) {
            txInputTypes.clear();
        }
        List<Integer> address = new ArrayList<>(3);
        address.add(UCaculateUtils.changeNum(44));
        address.add(UCaculateUtils.changeNum(0));
        address.add(UCaculateUtils.changeNum(0));
        for (SignIVDataResBody.Vin utxoBean : signIVDataResBody.getVin()) {

            TrezorMessageBitcoin.TxAck.TransactionType.TxInputType.Builder builder = TrezorMessageBitcoin.TxAck.TransactionType.TxInputType.newBuilder();
            builder.addAllAddressN(address)
                    .setAmount(Long.parseLong(utxoBean.getValue()))
                    .setPrevHash(ByteString.copyFrom(ClsPublicUtils.hexToBytes(utxoBean.getTxid())))
                    .setPrevIndex(utxoBean.getVout())
                    .setScriptType(TrezorMessageBitcoin.InputScriptType.SPENDP2SHWITNESS)
                    ;

            txInputTypes.add(builder.build());
        }
    }

    @Override
    public void initView() {
        bean = (JiedaiManagerBean) getIntent().getSerializableExtra("item");
        mContext = this;
        presenter.getData(bean.getId());
        presenter.getDataDetail(bean.getId());
    }

    /**
     * 0	待交割	7	待收款
     * 1	交割中	8	待补仓
     * 2	待抵押	9	待平仓
     * 3	已抵押	10	已逾期
     * 4	待还款	101	已平仓
     * 5	待付款	102	已结束(按钮隐藏)
     * 6	已付款	103	已取消(按钮隐藏) 104 待签名
     */
    private void initButton(OrderDetailResBody item) {
        if (item.getStatus() == 0) {
            tvLeft.setVisibility(View.VISIBLE);
            tvRight.setVisibility(View.VISIBLE);
            tvCommit.setVisibility(View.GONE);
            tvLeft.setText("撤销");
            tvRight.setText("交割");
        } else if (item.getStatus() < 4) {
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            tvCommit.setVisibility(View.VISIBLE);
            tvCommit.setText("交割");
        } else if (item.getStatus() == 8) {
            tvLeft.setVisibility(View.VISIBLE);
            tvRight.setVisibility(View.VISIBLE);
            tvCommit.setVisibility(View.GONE);
            tvLeft.setText("还款");
            tvRight.setText("补仓");
        } else if (item.getStatus() == 9) {
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            tvCommit.setVisibility(View.VISIBLE);
            tvCommit.setText("联系客服");
        } else if (item.getStatus() == 10 || item.getStatus() == 4) {
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            tvCommit.setVisibility(View.VISIBLE);
            tvCommit.setText("还款");
        } else if (item.getStatus() == 104) {
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            tvCommit.setVisibility(View.VISIBLE);
            tvCommit.setText("签名");
        } else if (item.getStatus() == 106 || item.getStatus() == 107 || item.getStatus() == 108) {
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            tvCommit.setVisibility(View.VISIBLE);
            tvCommit.setText("提币");
        } /*else if (item.getStatus() == 110) {
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            tvCommit.setVisibility(View.VISIBLE);
            tvCommit.setText("确认");
        } */ else {
            tvLeft.setVisibility(View.GONE);
            tvRight.setVisibility(View.GONE);
            tvCommit.setVisibility(View.GONE);
        }

    }

    @OnClick(R.id.bt_back)
    public void backClick() {
        finish();
    }

    @OnClick(R.id.btn_left)
    public void leftClick() {
        if (tvLeft.getText().toString().equals("还款")) {
            startActivity(HuanKuanActivity.class);
        } else if (tvLeft.getText().toString().equals("撤销")) {
            presenter.revoke(bean.getId());
        }
    }

    @OnClick(R.id.btn_right)
    public void rightClick() {
        if (tvRight.getText().toString().equals("还款")) {
            startActivity(HuanKuanActivity.class);
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("orderNo", bean.getId());
            bundle.putInt("status", 8);//补仓
            IntentUtil.toActivity(WaitDeliveryActivity.class, this, bundle);
        }
    }

    @OnClick(R.id.btn_commit)
    public void commitClick() {
        if (tvCommit.getText().toString().equals("还款")) {
            startActivity(HuanKuanActivity.class);
        } else if (tvCommit.getText().toString().equals("交割")) {
            Bundle bundle = new Bundle();
            bundle.putString("orderNo", bean.getId());
            IntentUtil.toActivity(WaitDeliveryActivity.class, this, bundle);
        }else if(tvCommit.getText().toString().equals("联系客服")){

        }else if(tvCommit.getText().toString().equals("提币")){
            IntentUtil.toActivity(WalletActivity.class ,this);
        }else if(tvCommit.getText().toString().equals("签名")){
            presenter.getSignData(bean.getOrderNo());
        }

    }

    private UsbManager usbManager;//usb管理器
    private UsbDevice mUsbDevice;//找到的usb设备
    private UsbInterface mUsbInterface;
    private UsbDeviceConnection mUsbDeviceConnection;

    private void checkUsb() {
        if (usbManager == null) {
            return;
        }
        HashMap<String, UsbDevice> deviceHashMap = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceHashMap.values().iterator();
        ArrayList<String> usbDeviceList = new ArrayList<>();//存放usb数量
        while (deviceIterator.hasNext()) {
            UsbDevice device = deviceIterator.next();
            usbDeviceList.add(String.valueOf(device.getVendorId()));
            usbDeviceList.add(String.valueOf(device.getProductId()));
            if (device.getVendorId() == 0x1209 && device.getProductId() == 0x53C1) {//找到我们的usb设备
                ToastUtils.ShowToast(mContext, "找到了对应的usb设备（硬件钱包）");
                mUsbDevice = device;
            }
        }
        //请求权限
        if (mUsbDevice == null) {
            ToastUtils.ShowToast(mContext, "没找到对应的usb设备");
            return;
        }
        if (usbManager.hasPermission(mUsbDevice)) {
            findIntfAndEpt();
        } else {
            getUsbPermission(mUsbDevice);
        }
    }

    /**
     * 寻找接口和分配结点
     */
    private UsbEndpoint usbEndpointIn;
    private UsbEndpoint usbEndpointOut;

    private void findIntfAndEpt() {
        if (mUsbDevice == null) {
            return;
        }
        if (mUsbDevice.getInterfaceCount() <= 0) {
            return;
        }
        mUsbInterface = mUsbDevice.getInterface(0);
        //打开设备，获取UsbDeviceConnection对象，连接设备，用于后面的通讯
        UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(mUsbDevice);
        if (usbDeviceConnection == null) {
            return;
        }
        if (usbDeviceConnection.claimInterface(mUsbInterface, true)) {
            //找到接口
            mUsbDeviceConnection = usbDeviceConnection;
            //用于UsbDeviceConnection与UsbInterface进行端点设置和通讯
            if (mUsbInterface.getEndpoint(0) != null) {
                usbEndpointIn = mUsbInterface.getEndpoint(0);
            }
            if (mUsbInterface.getEndpoint(1) != null) {
                usbEndpointOut = mUsbInterface.getEndpoint(1);
            }
        } else {
            //断开连接
            usbDeviceConnection.close();
        }
    }

    //开始申请USB权限
    private void getUsbPermission(UsbDevice mUSBDevice) {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(BeemIntent.ACTION_USB_INTENT), 0);
        IntentFilter filter = new IntentFilter(BeemIntent.ACTION_USB_INTENT);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        if (mUsbReceiver == null) {
            mUsbReceiver = new Receiver();
        }
        mContext.registerReceiver(mUsbReceiver, filter);
        usbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框/等待权限
    }

    private class Receiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BeemIntent.ACTION_USB_INTENT.equals(action)) {
                synchronized (this) {
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                            && mUsbDevice.equals(device)) {
                        //TODO 授权成功，操作USB设备
                        ToastUtils.ShowToast(mContext, "usb授权成功");
                    } else {
                        //用户点击拒绝了
                        ToastUtils.ShowToast(mContext, "拒绝usb授权");
                    }
                }
            }
        }
    }
}
